#!/bin/bash

# RocketMQ C++ 客户端动态库安装脚本
# 支持 macOS ARM64 (M1/M2/M3) 和 x86_64 架构

set -e

echo "🚀 开始安装 RocketMQ C++ 客户端动态库..."

# 检查系统架构
ARCH=$(uname -m)
echo "📋 检测到系统架构: $ARCH"

# 检查 Python 架构
PYTHON_ARCH=$(python3 -c "import platform; print(platform.machine())")
echo "📋 Python 架构: $PYTHON_ARCH"

# 检查是否存在动态库
DYLIB_PATH="rocketmq-client-cpp/lib/librocketmq.dylib"
if [ ! -f "$DYLIB_PATH" ]; then
    echo "❌ 错误: 找不到动态库文件 $DYLIB_PATH"
    echo "请确保已下载 rocketmq-client-cpp 并包含 librocketmq.dylib"
    exit 1
fi

# 检查动态库架构
DYLIB_ARCH=$(file "$DYLIB_PATH" | grep -o "x86_64\|arm64" || echo "unknown")
echo "📋 动态库架构: $DYLIB_ARCH"

# 创建安装目录
INSTALL_DIR="/usr/local/lib"
echo "📁 安装目录: $INSTALL_DIR"

# 检查是否有管理员权限
if [ ! -w "$INSTALL_DIR" ]; then
    echo "⚠️  需要管理员权限来安装到 $INSTALL_DIR"
    echo "请使用 sudo 运行此脚本"
    exit 1
fi

# 安装动态库
echo "📦 正在安装动态库..."
sudo cp "$DYLIB_PATH" "$INSTALL_DIR/"
sudo chmod 755 "$INSTALL_DIR/librocketmq.dylib"

# 更新动态库缓存
echo "🔄 更新动态库缓存..."
sudo ldconfig 2>/dev/null || {
    echo "⚠️  ldconfig 不可用，尝试其他方法..."
    # macOS 通常不需要 ldconfig
}

# 设置环境变量
echo "🔧 设置环境变量..."

# 检查 shell 类型
SHELL_CONFIG=""
if [[ "$SHELL" == *"zsh"* ]]; then
    SHELL_CONFIG="$HOME/.zshrc"
elif [[ "$SHELL" == *"bash"* ]]; then
    SHELL_CONFIG="$HOME/.bash_profile"
    if [ ! -f "$SHELL_CONFIG" ]; then
        SHELL_CONFIG="$HOME/.bashrc"
    fi
fi

if [ -n "$SHELL_CONFIG" ]; then
    # 检查是否已经设置了 DYLD_LIBRARY_PATH
    if ! grep -q "DYLD_LIBRARY_PATH.*$INSTALL_DIR" "$SHELL_CONFIG" 2>/dev/null; then
        echo "" >> "$SHELL_CONFIG"
        echo "# RocketMQ C++ 客户端动态库路径" >> "$SHELL_CONFIG"
        echo "export DYLD_LIBRARY_PATH=\"$INSTALL_DIR:\$DYLD_LIBRARY_PATH\"" >> "$SHELL_CONFIG"
        echo "✅ 已添加到 $SHELL_CONFIG"
    else
        echo "ℹ️  DYLD_LIBRARY_PATH 已存在于 $SHELL_CONFIG"
    fi
else
    echo "⚠️  无法确定 shell 配置文件，请手动设置环境变量"
    echo "export DYLD_LIBRARY_PATH=\"$INSTALL_DIR:\$DYLD_LIBRARY_PATH\""
fi

# 为当前会话设置环境变量
export DYLD_LIBRARY_PATH="$INSTALL_DIR:$DYLD_LIBRARY_PATH"

echo ""
echo "✅ 安装完成！"
echo ""
echo "📋 安装信息:"
echo "   - 动态库位置: $INSTALL_DIR/librocketmq.dylib"
echo "   - 架构: $DYLIB_ARCH"
echo "   - 环境变量: DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH"
echo ""

# 架构兼容性检查
if [ "$ARCH" = "arm64" ] && [ "$DYLIB_ARCH" = "x86_64" ]; then
    echo "⚠️  架构兼容性警告:"
    echo "   - 您的系统是 ARM64 (M1/M2/M3)"
    echo "   - 动态库是 x86_64 架构"
    echo "   - 需要使用 Rosetta 2 运行 Python"
    echo ""
    echo "💡 建议解决方案:"
    echo "   1. 使用 Docker 环境（推荐）"
    echo "   2. 安装 x86_64 版本的 Python"
    echo "   3. 使用 arch -x86_64 python3 运行脚本"
    echo ""
fi

echo "🧪 测试安装..."
python3 -c "
import ctypes
try:
    lib = ctypes.CDLL('$INSTALL_DIR/librocketmq.dylib')
    print('✅ 动态库加载成功！')
except Exception as e:
    print(f'❌ 动态库加载失败: {e}')
    print('💡 请尝试重新启动终端或运行: source $SHELL_CONFIG')
"

echo ""
echo "🎉 安装完成！请重新启动终端或运行以下命令使环境变量生效："
if [ -n "$SHELL_CONFIG" ]; then
    echo "   source $SHELL_CONFIG"
fi 